<template>
  <el-dialog title="编辑个人信息" :visible.sync="visible">
    <el-form :model="user">
      <el-form-item label="用户名">
        <el-input v-model="user.name"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="/api/upload-avatar"  <!-- 假设的后端接口 -->
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="user.avatar" :src="user.avatar" class="avatar">
          <i v-if="!user.avatar" class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="updateUserInfo">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      user: {
        name: '王小虎',
        avatar: ''
      }
    };
  },
  methods: {
    handleAvatarSuccess(response, file) {
      this.user.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
      return isJPG || isPNG && isLt2M;
    },
    updateUserInfo() {
      // 发送请求到后端更新用户信息
      console.log('更新用户信息', this.user);
      this.visible = false;
    }
  }
};
</script>

<style>
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  line-height: 100px;
  text-align: center;
}
</style>
